#pragma once

#include "i2c_v1.hpp"
#include "yj_return.hpp"
#include <glog/logging.h>
#include <thread>
#include <chrono>
#include <math.h>

class tpa626
{
public:
    typedef enum
    {
        config_reg_addr = 0x00,
        shunt_vol_reg_addr = 0x01,
        bus_vol_reg_addr = 0x02,
        power_reg_addr = 0x03,
        current_reg_addr = 0x04,
        calibration_reg_addr = 0x05,
        mask_enable_reg_addr = 0x06,
        alert_limit_reg_addr = 0x07,
        mf_id_reg_addr = 0xfe,
        die_id_reg_addr = 0xff
    } reg_addr;

private:
    std::string _dev_name;
    i2c_v1 *_i2c;
    uint8_t _device_address;
    double _max_measure_current; // 最大希望的采样电流，单位A
    double _shunt_res;           // 采样电阻，单位R
    uint16_t _shunt_calibation;  // 采样电阻校准值
    double _current_lsb;

    yj_return _flag;

    yj_return _read_reg(reg_addr reg, uint16_t *data, uint8_t len);
    yj_return _write_reg(reg_addr reg, uint16_t *data, uint8_t len);

public:
    tpa626(std::string dev_name, i2c_v1 *i2c, uint8_t device_address, double max_measure_current, double shunt_res);
    ~tpa626();

    yj_return init();
    yj_return check_MIF_id_and_DIE_id();
    yj_return check_calibration_reg_is_ok();

    yj_return reset();

    yj_return read_status();
    yj_return read_single_reg(reg_addr reg, uint16_t *reg_out);

    yj_return read_power(double *power);
    yj_return read_current(double *current);
    yj_return read_bus_vol(double *bus_vol);
    yj_return read_power_current_bus_vol(double *power, double *current, double *bus_vol);
    yj_return read_config_reg(uint16_t *config_reg);
    yj_return read_calibration_reg(uint16_t *calibration_reg);

    void print_config();
};